#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv){
    int fd, flags;
    unsigned long byteCount = 0;
    char writedData = 'a';
    mode_t mode = S_IRUSR | S_IWUSR | S_IROTH | S_IWOTH;

    if(argc == 3){
        flags = O_CREAT | O_WRONLY | O_APPEND;
    }
    else if (argc == 4){
        flags = O_CREAT | O_WRONLY ;
    }
    else {
        printf("Error you must use programm filename byte_count, or filename byte_count x\n");
        exit(EXIT_FAILURE);
    }

    byteCount = strtoul(argv[2], NULL, 10);
    if(byteCount == 0){
        printf("Error get byteCount %s\n", argv[1]);
        exit(EXIT_FAILURE);        
    }

    fd = open(argv[1], flags, mode);
    if(fd == -1){
        printf("Error open file %s %s\n", argv[1], strerror(errno));
        exit(EXIT_FAILURE);
    }

    if(argc == 3){
        while(byteCount--){
            if (write(fd, &writedData, 1) == -1){
                printf("Error write file %s %s\n", argv[1], strerror(errno));
                exit(EXIT_FAILURE);                
            }
        }     
    }
    else if(argc == 4){
        while(byteCount--){
            if (lseek(fd, 0, SEEK_END) == -1){
                printf("Error lseek file %s %s\n", argv[1], strerror(errno));
                exit(EXIT_FAILURE);                  
            }
            if (write(fd, &writedData, 1) == -1){
                printf("Error write file %s %s\n", argv[1], strerror(errno));
                exit(EXIT_FAILURE);                
            }
        }    
    }

    if (close(fd) == -1){
        printf("Error close file %s %s\n", argv[1], strerror(errno));
        exit(EXIT_FAILURE);          
    }
}